#include "RenderBuffer.hpp"


ReflectBuffer::ReflectBuffer() {
	glGenRenderbuffers(1,&depthBuffer);
	glBindRenderbuffer(GL_RENDERBUFFER,depthBuffer);
	glRenderbufferStorage(GL_RENDERBUFFER,GL_DEPTH_COMPONENT24,1024,768);

	reflectBuffer = new GLuint[1];
	glGenFramebuffers(1,reflectBuffer);
	cout << "id of reflectBuffer : " << reflectBuffer[0] << endl;

	renderToTexture = 0;
	glGenTextures(1, &renderToTexture);
	cout << " id : render to texture : " << renderToTexture << endl;
	glBindTexture(GL_TEXTURE_2D,renderToTexture);
	glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA8,1024,768,0,GL_RGBA,GL_UNSIGNED_BYTE,NULL);

	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, reflectBuffer[0]);
	glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderToTexture, 0);
	glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer);

	// binding back the standard FrameBuffer
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER,0);	
}

void ReflectBuffer::set() {
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, reflectBuffer[0]);
	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
	glViewport(0.0,0.0,1024,768);
	glClearColor(0.0,0.0,1.0,1.0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity(); 
	glOrtho(0.0f,1.0f,0.0f,1.0f,-2.0f,2.0f);
	glMatrixMode(GL_MODELVIEW);            
	glLoadIdentity();
}

void ReflectBuffer::unset() {
	glBindTexture(GL_TEXTURE_2D,renderToTexture);
	glGenerateMipmap(GL_TEXTURE_2D);	
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER,0);
};
